<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 渲染数据表格 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              v-for="(item1,index1) in scope.row.children"
              :key="index1.id"
              :class="[index1 === 0 ? 'colOne':'','dbcol','domCenter']"
            >
              <el-col :span="5">
                <el-tag closable @close="deleteTag(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  v-for="(item2,index2) in item1.children"
                  :key="index2.id"
                  :class="[index2 === 0 ? '' : 'colOne','domCenter']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="deleteTag(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-row>
                      <el-col>
                        <el-tag
                          type="warning"
                          v-for="(item3,index3) in item2.children"
                          :key="index3.id"
                          closable
                          @close="deleteTag(scope.row,item3.id)"
                        >{{item3.authName}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRoles(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoles(scope.row.id)">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="rightGrant(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="rightDialogVisible" width="60%" @close="resetRightList">
      <!-- 树形控件 -->
      <!-- :props绑定属性 show-checkbox节点是否可被选择  default-expand-all全部展开 default-checked-keys默认勾选 node-key唯一标识-->
      <el-tree
        :data="rightList"
        :props="rightProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="keys"
        ref="domRight"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="60%" @close="closeAddDialogVisible">
      <el-form :model="addRolesForm" :rules="rolesRules" ref="rolesFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAddroles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="60%" @close="closeEditDialogVisible">
      <el-form :model="editRolesList" :rules="editRolesRules" ref="editRolesFormRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesList.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesList.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditroles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 获取角色数据
      rolesList: [],
      // 权限对话框
      rightDialogVisible: false,
      // 获取所有权限列表
      rightList: [],
      // 为树形控件绑定属性
      rightProps: {
        children: 'children',
        label: 'authName'
      },
      // 树形控件默认选中的内容
      keys: [],
      // 当前角色的id
      rightId: '',
      // 添加角色信息
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 添加角色表单验证
      rolesRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 获取编辑角色的信息
      editRolesList: [],
      // 编辑角色对话框的显示与隐藏
      editDialogVisible: false,
      // 编辑角色表单验证
      editRolesRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色权限
    async getRolesList() {
      const { data: res } = await this.axios.get('roles')
      if (res.meta.status !== 200) return this.msg.error('获取角色列表失败')
      this.rolesList = res.data
    },
    // 删除角色指定权限
    async deleteTag(roles, id) {
      const result = await this.cof('此操作将永久删除权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 点击取消返回一个cancel字符串
      // 点击确认返回一个confirm字符串
      if (result !== 'confirm') {
        return this.msg('你取消了删除')
      }
      const { data: res } = await this.axios.delete(`roles/${roles.id}/rights/${id}`)
      if (res.meta.status !== 200) return this.msg.error('删除用户失败')
      this.msg('删除用户成功')
      // 返回的data, 是当前角色下最新的权限数据，重新赋值就可以了
      roles.children = res.data
    },
    // 渲染分配所有权限树
    async rightGrant(roles) {
      // 当前角色的id
      this.rightId = roles.id
      const { data: res } = await this.axios.get('rights/tree')
      if (res.meta.status !== 200) return this.msg('获取所有权限列表失败')
      this.rightList = res.data
      // roles是指定角色的权限
      this.getKeysArr(roles, this.keys)
      this.rightDialogVisible = true
    },
    // 利用递归获取树形控件默认选中的内容(获取三级内容里面的id)
    getKeysArr(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      // 利用递归获取一级二级节点里面的三级节点内容
      node.children.forEach(item => this.getKeysArr(item, arr))
    },
    // 关闭对话框，清空里面数据
    resetRightList() {
      this.keys = []
    },
    // 点击确定完成角色授权
    async submitRights() {
      // 全选内容(获取三级的id)
      const checkout = this.$refs.domRight.getCheckedKeys()
      // 半选(获取一级二级的id)
      const half = this.$refs.domRight.getHalfCheckedKeys()
      const rids = [
        ...checkout,
        ...half
      ].join(',')
      const { data: res } = await this.axios.post(`roles/${this.rightId}/rights`, { rids })
      if (res.meta.status !== 200) return this.msg.error('角色授权失败')
      this.getRolesList()
      this.rightDialogVisible = false
    },
    // 添加角色表单预校验
    submitAddroles() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.axios.post('roles', this.addRolesForm)
          if (res.meta.status !== 201) return this.msg.error('添加角色失败')
          this.msg('添加角色成功')
          this.addDialogVisible = false
          this.getRolesList()
        }
      })
    },
    // 添加角色对话框关闭后重置表单
    closeAddDialogVisible() {
      this.$refs.rolesFormRef.resetFields()
    },
    // 获取编辑角色信息
    async editRoles(id) {
      const { data: res } = await this.axios.get('roles/' + id)
      if (res.meta.status !== 200) return this.msg.error('获取用户角色信息失败')
      this.editRolesList = res.data
      this.editDialogVisible = true
    },
    // 编辑角色表单预验证
    submitEditroles() {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.axios.put('roles/' + this.editRolesList.roleId, this.editRolesList)
          if (res.meta.status !== 200) return this.msg.error('编辑用户角色失败')
          this.msg('编辑用户角色成功')
          this.getRolesList()
          this.editDialogVisible = false
        }
      })
    },
    // 编辑角色对话框关闭后重置表单
    closeEditDialogVisible() {
      this.$refs.editRolesFormRef.resetFields()
    },
    // 点击删除角色
    async deleteRoles(id) {
      // this.cof返回的是一个Promise对象
      const result = await this.cof('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 捕捉错误并且返回这个错误
      // 点击取消返回一个cancel字符串
      // 点击确认返回一个confirm字符串
      if (result !== 'confirm') {
        return this.msg('你取消了删除')
      }
      const { data: res } = await this.axios.delete('roles/' + id)
      if (res.meta.status !== 200) return this.msg.error('删除角色失败')
      this.msg('删除角色成功')
      this.getRolesList()
    }
  }
}
</script>

<style scoped lang="less">
  .colOne {
    border-top: 1px solid #000;
  }
  .dbcol {
    border-bottom: 1px solid #000;
  }
  .el-row {
    padding: 7px 0;
  }
  .domCenter {
    display: flex;
    align-items: center;
  }
</style>
